//
//  JBWOAuthViewController.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/7/1.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit

class JBWOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    
    //取消关闭控制器
    @objc private func canceClick(){
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFillClick(){
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(JBWWBNAME)';document.getElementById('passwd').value='\(JBWWBPASSWD)'"
        //JS注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    }

    
    private func setupUI(){
        setNav()
        view.backgroundColor = UIColor.white
    }
    
    private func setNav(){
        navigationItem.title = "微博登陆"
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(canceClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: nil, title: "自动填充", target: self, action: #selector(autoFillClick))
    }
    
    
    //webView
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self 
        // urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(JBWAPPKEY)&redirect_uri=\(JBWREDIRECT_URI)"
        print(urlString)
        
        let url = URL(string: urlString)
        //判断字符串是否为nil
        guard let u = url else {
            return webView
        }
        webView.loadRequest(URLRequest(url:u))
        return webView
        
    }()
    
}

extension JBWOAuthViewController:UIWebViewDelegate {
    
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    }
    
    //监听将要加载的request 
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //通过request得到对应的URLString
        let urlString = request.url?.absoluteString
        //判断urlString是否为nil 及是否前缀是否为我们设置的回调页
        //判断字符串的前缀hasPrefix后缀hassuffix
        if let u  = urlString, u.hasPrefix(JBWREDIRECT_URI) {
            //获取地址的请求参数部分 判断是否为nil
            if let query = request.url?.query {
                print("参数query",query)
                //得到code
                let code = query.substring(from: "code=".endIndex)
                print("得到啦code",code)
            
                JBWOAuthViewModel.share.getUserAccount(code: code, finash: { (isFinash) in
                    if !isFinash{
                        print("请求失败")
                    } else {
                        print("请求成功")
                        //关闭控制器
                        self.dismiss(animated: false, completion: {
                            //发送通知
                            NotificationCenter.default.post(name: JBWSWITCHVIEWCONTROLLERNOTI, object: nil)
                        })
                    }
                })
            }
        }
        return true
    }
}
